package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.NewsDao;
import entity.News;

public class NewsDaoImpl extends BaseDaoImpl<News> implements NewsDao{

	@Override
	public List<News> getAllNews() {
		String sql="SELECT * FROM News ORDER BY PublishDate DESC";
		return showAll(sql);
	}

	@Override
	public List<News> listByRs(ResultSet rs) {
		List<News> list =new ArrayList<News>();
		try {
			while(rs.next()){
				list.add(new News(rs.getInt("id"),
						rs.getString("title"),
						rs.getString("content"),
						rs.getDate("publishdate"),
						rs.getInt("userid")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void deletenews(int id) {
		String sql = "DELETE FROM News WHERE id=?";
		CUDObject(sql, id);
		
	}

	@Override
	public void addNews(News n) {
		String sql = "INSERT INTO News(Title,Content,PublishDate,UserId) VALUES (?,?,?,?)";
		CUDObject(sql, n.getTitle(),n.getContent(),n.getPublishdate(),n.getUserid());
	}

	@Override
	public List<News> getNewsBySearch(String s) {
		StringBuffer sql=new StringBuffer();
		List parms = new ArrayList();
		if(s!=null){
			sql.append("SELECT * FROM News WHERE title LIKE ?");
			parms.add("%"+s+"%");
		}else{
			sql.append("SELECT * FROM News");
		}
		return showAll(sql.toString(), parms.toArray());
	}

	@Override
	public News getNewsById(int id) {
		String sql = "SELECT * FROM News WHERE id = ?";
		return showAll(sql, id).get(0);
	}

	@Override
	public void updateNews(News n) {
		String sql = "UPDATE news SET Title=?,Content=?,PublishDate=?,UserId=? WHERE id=?";
		CUDObject(sql, n.getTitle(),n.getContent(),n.getPublishdate(),n.getUserid(),n.getId());
	}

}
